<?php

namespace app\adminapi\logic\system;

use adminmatrix\admin\annotation\Inject;
use adminmatrix\admin\logic\BaseLogic;
use app\adminapi\model\system\AdminSystem;
use app\Request;
use think\exception\HttpException;

class ConfigLogic extends BaseLogic
{
    #[Inject]
    protected AdminSystem $model;


    public function addGroup(Request $request) : bool
    {
        try {
            return $this->model->save($request->post());
        } catch (HttpException $e)
        {
            throw new HttpException(200 , $e->getMessage());
        }
    }


    public function save(Request $request ) : bool
    {
        try {
            $params = $request->post();
            $result = $this->model->where('id' , $params['group_id'])->findOrEmpty();
            if ($result->isEmpty()) throw new HttpException(200 , '不存在配置标签');
            $result->config()->save($params);
            return true;

        } catch (HttpException $e)
        {
            throw new HttpException(200 , $e->getMessage());
        }
    }


    public function updateConfig(Request $request)
    {
        try {
            $params = $request->put();
            $result = $this->model->where('id' , $params['group_id'])->findOrEmpty();
            if ($result->isEmpty()) throw new HttpException(200 , '不存在配置标签');
            $result ->config->update($params);
           return true;
        } catch (HttpException $e)
        {
            throw new HttpException($e->getCode() , $e->getMessage());
        }
    }

    public function deleteConfig(Request $request)
    {
        try {
            $params = $request->put();
            $result = $this->model->where('id' , $params['group_id'])->findOrEmpty();
            if ($result->isEmpty()) throw new HttpException(200 , '不存在配置标签');
            $result ->config()->where('id' , $params['id'])->delete();
            return true;
        } catch (HttpException $e)
        {
            throw new HttpException($e->getCode() , $e->getMessage());
        }
    }
}